package point

import (
	"net"
)

type WanXSubNetMaskPoint struct {
	index int
}

var wanxSubNetMask string

func NewWanXSubNetMaskPoint() *WanXSubNetMaskPoint { return &WanXSubNetMaskPoint{} }

func (s *WanXSubNetMaskPoint) Get() any {
	var interfaceName string

	if s.index == 0 {
		interfaceName = "eth1"
	} else if s.index == 1 {
		interfaceName = "eth2"
	} else {
		return ""
	}

	getInterfaceNetMask := func(interName string) string {
		iface, err := net.InterfaceByName(interName)
		if err != nil {
			return ""
		}

		addrs, err := iface.Addrs()
		if err != nil {
			return ""
		}

		for _, addr := range addrs {
			if ipNet, ok := addr.(*net.IPNet); ok {
				return net.IP(ipNet.Mask).String()
			}
		}

		return ""
	}

	return getInterfaceNetMask(interfaceName)

}

func (m *WanXSubNetMaskPoint) Set(val ...any) bool {
	if len(val) < 1 {
		return false
	}

	if subNetMask, ok := val[0].(string); ok {
		wanxSubNetMask = subNetMask
	}

	return true
}

func (m *WanXSubNetMaskPoint) SetRoute(str string) PointInterface {
	m.index = int(str[len("wan")]) - '0'
	return m
}
